<?php

namespace app\common\service\auth;

use app\api\controller\v2\Auth;
use app\model\AgentChannel;
use app\model\MobileUser;
use think\facade\Db;

class AuthApiService extends AuthBase implements AuthInterface
{

    /**
     * @var MobileUser $user
     */
    public $user;

    /**
     * @var AgentChannel $agentChannel
     */
    public $agentChannel;


    public function attempt($params)
    {

        if (!empty(input('_user_id')) && !isProd()) {
            return $this->user = MobileUser::query()
                ->where('id', input('_user_id'))
                ->find();
        }
        $token = request()->header('Authorization') ?? request()->header('token');  //小程序Authorization请求无效

        if (empty($token)) {
            return false;
        }
        $cache = cache(Auth::TOKENKEY . $token);
        /**
         * @var MobileUser $user
         */
        if ($cache) {
            $user = unserialize($cache);
        } else {
            $user = MobileUser::query()
                ->where('token', $token)
                ->find();
        }

        $this->user = $user;

        //过期时间拿到外层判断

        if (empty($user)) {
            return false;
        }

        return $user->toArray();

    }

    /**
     * 验证渠道
     */
    public function attemptChannel()
    {
        $channel = input('channel');
        if (empty($channel)) {
            return false;
        }
        $agentChannel = AgentChannel::query()
            ->field('id, name, agent_id, template_id, state')
            ->where('name', $channel)
            ->cache('attemptChannel' . $channel, 60)
            ->where('is_deleted', 0)
            ->find();

        if (empty($agentChannel)) {
            return false;
        }
        $this->agentChannel = $agentChannel;

        return $agentChannel;
    }


    public function login($params)
    {

    }

    public function id()
    {
        return $this->user->id;
    }

    /**
     * @return MobileUser
     */
    public function user()
    {
        return $this->user;
    }

    public function channelId()
    {
        // 如果这边报错检查是否实例化 Auth::attemptChannel()

        return $this->agentChannel->id;
    }

    public function agentId()
    {
        // 如果这边报错检查是否实例化 Auth::attemptChannel()
        return $this->agentChannel->agent_id;
    }


}